package top.hkyzf.study.leetcode.math;

import org.junit.Test;

import java.util.Stack;

/**
 * @author zhufeng
 * @version 1.0
 * @date 2020-12-19 11:40
 */
public class 整数反转_7 {
    @Test
    public void testReverse() {
        int result = reverse(123456);
        System.out.println("结果为：" + result);
    }

    // 刚学了栈，练习一下
    public int reverseByStack(int x) {
        Stack<Character> stack = new Stack<Character>();
        char [] chars = String.valueOf(x).toCharArray();
        // true为正数
        boolean flag = true;
        if(chars[0] == '-') {
            flag = false;
            for(int i=1; i<chars.length; i++) {
                stack.push(chars[i]);
            }
        } else {
            for(int i=0; i<chars.length; i++) {
                stack.push(chars[i]);
            }
        }
        char [] rs = new char[stack.size()];
        int i = 0;
        while (!stack.empty()) {
            rs[i] = stack.pop();
            i++;
        }
        String result_str = String.valueOf(rs);
        // 负数
        if(!flag) {
            result_str = "-" + result_str;
        }

        Integer result = null;
        try {
            result = Integer.valueOf(result_str);
        } catch (NumberFormatException e) {
            //输入合法的情况下抛异常为溢出
            result = 0;
        }
        return result;
    }

    public int reverse(int x) {
        // result 每次循环扩大十倍， 输入的 x 每次循环缩小十倍
        int result = 0;
        while(x != 0) {
            // 暂存上次处理结果
            int temp = result;
            result = result * 10 + x % 10;
            x = x /10;
            // 判断溢出
            if (temp != result/10) {
                return 0;
            }
        }
        return result;
    }
}
